#pragma once
#include <iostream>
using namespace std;
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <functional>
#include "log.hpp"

namespace Client
{
    class tcpClient
    {
    public:
        tcpClient(const uint16_t &port = 8080, const string &ip = "0.0.0.0") : _sock(-1), _serverport(port), _serverip(ip)
        {
        }
        void initClient()
        {
            // 1：启动套接字
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock < 0)
            {
                logMessage(4, "socket errno");
                exit(1);
            }
            logMessage(1, "socket success");
        }

        void start()
        {
            // 2:与服务器建立连接：3次握手
            sockaddr_in server;
            bzero(&server, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            int ret = connect(_sock, (sockaddr *)&server, sizeof(server));
            if (ret < 0)
            {
                logMessage(4, "connect fail");
            }
            else if (ret == 0)
            {
                logMessage(1, "connect success");

                // 发送数据给服务器
                string line;
                while (1)
                {
                    cout << "请输入小写字母";
                    getline(cin, line);
                    write(_sock, line.c_str(), line.size());

                    // 回显的数据
                    char buffer[1024];
                    int n = read(_sock, buffer, sizeof(buffer) - 1);
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        cout << "server回显：" << buffer << endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        ~tcpClient()
        {
        }

    private:
        int _sock;
        uint16_t _serverport;
        string _serverip;
    };
}